<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item v-if="sensor.sensorId">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-cpu"
          type="primary"
          @click="gotoSensor()"
        >{{ $t('sensor') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="sensorId"
          @change="sensorChange"
        >
          <el-option
            v-for="item in sensorList"
            :key="item.sensorId"
            :label="$t('port')+':'+item.port + ' ['+item.sensorName+']'"
            :value="item.sensorId"
          />
        </el-select>
        <el-form-item>
          <el-input
            v-model="name"
            clearable
            :placeholder="$t('name')"
            @change="listSensorWith"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="listSensorWith">{{ $t('search') }}</el-button>
        </el-form-item>
      </el-form-item>
    </el-form>

    <el-table
      ref="paramTable"
      :data="paramList"
      style="width: 100%"
    >
      <el-table-column :label="$t('icon')" width="80">
        <template slot-scope="scope">
          <img
            :src="scope.row.iconUrl"
            style="width: 20px;height: 20px;margin-top: 5px"
          >
        </template>
      </el-table-column>
      <el-table-column prop="name" :label="$t('name')" />
      <el-table-column prop="remark" :label="$t('remark')" />
      <el-table-column prop="keyName" :label="$t('keyName')" />
      <el-table-column prop="value" :label="$t('value')" />
      <el-table-column prop="unit" :label="$t('unit')" />
      <el-table-column prop="type" :label="$t('created')+$t('type')" :formatter="formatterCreatedType" />
      <el-table-column :label="$t('hidden')" width="115">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.hidden"
            @change="hidden(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('brand')" width="115">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.brand"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column width="210" :label="$t('function')">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-menu"
            @click="version(scope.row)"
          >{{ $t('version') }}
          </el-button>
          <el-button
            :disabled="scope.row.brand"
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            :disabled="scope.row.brand"
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog

      :visible.sync="dialogFormVisible"
    >
      <el-form
        label-width="20%"
      >
        <el-form-item :label="$t('name')">
          <el-autocomplete
            v-model="param.name"
            :disabled="param.paramId"
            :fetch-suggestions="nameSearch"
            @select="nameChange"
          />
        </el-form-item>
        <el-form-item :label="$t('keyName')">
          <el-autocomplete
            v-model="param.keyName"
            :disabled="param.paramId"
            :fetch-suggestions="keyNameSearch"
            @select="keyNameChange"
          />
        </el-form-item>
        <el-form-item :label="$t('remark')">
          <el-input v-model="param.remark" />
        </el-form-item>
        <el-form-item :label="$t('value')">
          <el-input v-model="param.value" />
        </el-form-item>
        <el-form-item :label="$t('unit')">
          <el-input v-model="param.unit" />
        </el-form-item>
        <el-form-item :label="$t('icon')">
          <el-input v-model="param.iconUrl">
            <template slot="prepend">
              <el-image
                style="width: 20px;height: 20px;margin-top: 2px"
                :src="param.iconUrl"
              />
            </template>
            <template slot="append">
              <i class="el-icon-caret-bottom" @click="choseIcon" />
            </template>
          </el-input>
          <div v-show="isIconOpen">
            <el-image
              v-for="(item,index) in iconList"
              :key="index"
              style="margin: 5px;cursor: pointer;width: 40px;height: 40px"
              :src="item.url"
              @click="changeIco(item.url,200145308)"
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('hidden')">
          <el-switch
            v-model="param.hidden"
          />
        </el-form-item>
        <el-form-item :label="$t('brand')">
          <el-switch
            v-model="param.brand"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('version')"
      :visible.sync="showVersionList"
    >
      <el-table
        :data="versionList"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('createdDate')"
          sortable
        >
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span style="margin-left: 13px">{{ formatDate(scope.row.createdDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="value"
          :label="$t('value')"
        />
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import {
  failureNotice,
  successNotice,
  cancelNotice,
  formatterCreatedType,
  formatDate
} from '@/util/common'
import {
  listSensorWith
} from '@/api/iot/iotDeviceSensorApi'
import {
  updateDeviceParam,
  insertDeviceParam,
  deleteDeviceParam,
  updateDeviceParamList,
  listDeviceParamVersion,
  listDeviceParamIcon, listDeviceParam
} from '@/api/iot/iotDeviceParamApi'
import { listProductTemplateParam } from '@/api/iot/iotProductTemplateParamApi'

export default {
  name: 'DeviceParam',
  data() {
    return {
      name: null,
      iconList: [],
      dialogFormVisible: false,

      paramList: [],
      sensorList: [],
      sensor: {},
      sensorId: null,
      param: {
        paramId: null,
        name: null,
        keyName: null,
        value: null,
        unit: null,
        iconUrl: null,
        hidden: null
      },
      deviceCore: null,
      deviceName: null,
      isIconOpen: false,
      productTemplateList: [],
      showVersionList: false,
      versionList: [],
      nameList: [],
      keyNameList: []
    }
  },
  mounted() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    this.sensorId = param.sensorId ? parseInt(param.sensorId) : null
    this.listSensorWith()
    this.listDeviceParamIcon()
    this.listProductTemplateParam()
    this.setTagsViewTitle()
  },
  methods: {
    gotoSensor() {
      this.$router.push({
        path: '/device/sensor/' + this.deviceCore,
        query: { deviceCore: this.deviceCore, deviceName: this.deviceName }
      })
    },
    sensorChange() {
      this.sensorList.forEach(sensor => {
        if (this.sensorId === sensor.sensorId) {
          this.sensor = sensor
          const paramList = []
          if (this.name) {
            sensor.paramList.forEach(param => {
              if (param.name.indexOf(this.name) >= 0) {
                paramList.push(param)
              }
            })
            this.paramList = paramList
          } else {
            this.paramList = sensor.paramList
          }
          this.$nextTick(() => {
            this.setSort()
          })
        }
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    nameSearch(queryString, cb) {
      const nameList = this.nameList
      const results = queryString ? nameList.filter(this.createFilter(queryString)) : nameList
      cb(results)
    },
    keyNameSearch(queryString, cb) {
      const keyNameList = this.keyNameList
      const results = queryString ? keyNameList.filter(this.createFilter(queryString)) : keyNameList
      cb(results)
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    listDeviceParam() {
      this.paramList = []
      listDeviceParam({
        sensorId: this.sensor.sensorId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.paramList = data
          this.$nextTick(() => {
            this.setSort()
          })
        }
      })
    },
    setSort() {
      const el = this.$refs.paramTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.paramList.splice(evt.oldIndex, 1)[0]
          this.paramList.splice(evt.newIndex, 0, targetRow)
          const updateList = []
          for (let i = 0, j = this.paramList.length; i < j; i++) {
            const param = this.paramList[i]
            const data = {
              rankNumber: i,
              paramId: param.paramId
            }
            updateList.push(data)
          }

          updateDeviceParamList({
            deviceParamList: updateList
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(this)
              this.listDeviceParam()
            }
          })
        }
      })
    },
    keyNameChange(item) {
      this.param.keyName = item.value
      for (let i = 0; i < this.productTemplateList.length; i++) {
        if (this.productTemplateList[i].keyName === item.value) {
          this.param.name = this.productTemplateList[i].name
          this.param.iconUrl = this.productTemplateList[i].iconUrl
          this.param.value = this.productTemplateList[i].value
          this.param.unit = this.productTemplateList[i].unit
          this.param.hidden = this.productTemplateList[i].hidden
          this.param.rankNumber = this.productTemplateList[i].rankNumber
        }
      }
    },
    nameChange(item) {
      this.param.name = item.value
      for (let i = 0; i < this.productTemplateList.length; i++) {
        if (this.productTemplateList[i].name === item.value) {
          this.param.keyName = this.productTemplateList[i].keyName
          this.param.iconUrl = this.productTemplateList[i].iconUrl
          this.param.value = this.productTemplateList[i].value
          this.param.unit = this.productTemplateList[i].unit
          this.param.hidden = this.productTemplateList[i].hidden
          this.param.rankNumber = this.productTemplateList[i].rankNumber
        }
      }
    },
    listProductTemplateParam() {
      listProductTemplateParam({
        deviceCore: this.deviceCore
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.productTemplateList = data
          const nameList = []
          const keyNameList = []
          data.forEach(item => {
            nameList.push({ value: item.name })
            keyNameList.push({ value: item.keyName })
          })
          this.nameList = nameList
          this.keyNameList = keyNameList
        } else {
          this.productTemplateList = []
          this.nameList = []
          this.keyNameList = []
        }
      })
    },
    listDeviceParamIcon() {
      listDeviceParamIcon({}).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.iconList = data
        }
      })
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    choseIcon() {
      if (this.isIconOpen) {
        this.isIconOpen = false
      } else {
        this.isIconOpen = true
      }
    },
    changeIco(iconUrl) {
      this.isIconOpen = false
      this.param.iconUrl = iconUrl
    },
    formatterCreatedType(item) {
      return formatterCreatedType(this, item.type)
    },
    version(item) {
      listDeviceParamVersion({
        paramId: item.paramId
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.versionList = data
          this.showVersionList = true
        } else {
          this.versionList = []
          this.showVersionList = true
        }
      })
    },
    edit(index) {
      this.param = index
      this.dialogFormVisible = true
    },
    del(index) {
      const that = this
      this.$confirm(this.$t('delete') + index.name, {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceParam({
            paramId: index.paramId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
            that.listSensorWith()
          }
          )
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withParam: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.sensorList = data
          let paramListRes
          if (this.sensorId) {
            data.forEach(sensor => {
              if (sensor.sensorId === this.sensorId) {
                this.sensor = sensor
                this.sensorId = this.sensor.sensorId
                paramListRes = sensor.paramList
                return
              }
            })
          } else {
            this.sensor = data[0]
            this.sensorId = this.sensor.sensorId
            paramListRes = data[0].paramList
          }
          const paramList = []
          if (this.name) {
            paramListRes.forEach(param => {
              if (param.name.indexOf(this.name) >= 0) {
                paramList.push(param)
              }
            })
            this.paramList = paramList
          } else {
            this.paramList = paramListRes
          }
          this.$nextTick(() => {
            this.setSort()
          })
        } else {
          this.sensorList = []
          this.sensor = {}
        }
      }
      )
    },

    showAdd() {
      this.param = {
        port: this.sensor.port,
        remark: '',
        unit: '',
        deviceCore: this.deviceCore,
        value: '',
        hidden: false,
        brand: false
      }
      this.dialogFormVisible = true
    },
    hidden(item) {
      updateDeviceParam({
        paramId: item.paramId,
        hidden: item.hidden
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    addOrUpdate() {
      if (this.param.name === '') {
        failureNotice(this, '请填写属性名称')
        return
      }
      if (this.param.keyName === '') {
        failureNotice(this, '请填写英文名')
        return
      }
      const json = {
        ...this.param
      }
      if (!this.param.paramId) {
        insertDeviceParam(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogFormVisible = false
          }
          this.listSensorWith()
        })
      } else {
        updateDeviceParam(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogFormVisible = false
          }
          this.listSensorWith()
        })
      }
    }
  }
}
</script>
